from pyjamas import DOM

from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.ui.HorizontalPanel import HorizontalPanel
from pyjamas.ui.HTML import HTML
from pyjamas.ui.Button import Button
from pyjamas.ui.TextBox import TextBox
from pyjamas.ui.ListBox import ListBox
from pyjamas.ui.Grid import Grid
from pyjamas.ui.UIObject import setStyleName

from pyjamas.Timer import Timer

from pyjamas.JSONService import JSONProxy

listRoot = RootPanel('logger_list')


class LoggerList(Grid):

    filters = ['domain', 'context', 'eventtype', 'msg_key', ]

    def __init__(self, app, **kwargs):
        self.app = app
        table = DOM.createTable()
        setStyleName(table, 'listing', True)
        self.thead = DOM.createElement('thead')
        DOM.appendChild(table, DOM.createTBody())
        DOM.appendChild(table, self.thead)
        self.batchSize = 20
        Grid.__init__(self, 21, 6, Element=table, **kwargs)
        self._setFilter()
        self._setHeader()
        self.addTableListener(self)
        for row in range(21):
            self.cellFormatter.addStyleName(row, 0, 'first')

    def setHeaderText(self, col, text):
        cell = DOM.getChild(self.thead, col)
        self.internalClearCell(cell)
        DOM.setInnerText(cell, text)

    def resizeColumns(self, columns):
        if self.numColumns == columns:
            return
        if self.numColumns < columns:
            for j in range(self.numColumns, columns):
                DOM.appendChild(self.thead, DOM.createTH())
        Grid.resizeColumns(self, columns)

    def setBatchSize(self, size):
        self.batchSize = size

    def _setHeader(self):
        self.setHeaderText(0, 'Timestamp')
        self.setHeaderText(1, 'Domain')
        self.setHeaderText(2, 'Context')
        self.setHeaderText(3, 'Type Of Event')
        self.setHeaderText(4, 'Key')
        self.setHeaderText(5, 'Value')

    def _setFilter(self):
        self.setText(0, 0, 'Filter:')
        for c, p in enumerate(self.filters):
            c += 1
            w = TextBox()
            setattr(self, p, w)
            self.setWidget(0, c, w)

    def startUpdate(self):
        self.onTimer()

    def onTimer(self):
        filters = []
        for f in self.filters:
            v = getattr(self, f).getText()
            if v:
                filters.append(('%s ='% f, v))
        self.app.proxy.query(filters, '-timestamp', 20, self)

    def onRemoteResponse(self, response, request_info):
        data = response['data']
        rLen = len(data)
        for r in range(20):
            if r < rLen:
                d = data[r]
                for c, p in enumerate(['timestamp',
                                       'domain', 'context', 'eventtype',
                                       'msg_key', 'msg_value'
                                      ]):
                    self.setText(r+1, c, d[p])
            else:
                for c in range(6):
                    self.setText(r+1, c, '')
        Timer(2000, self)

    def onRemoteError(self, code, error, request_info):
        self.setText(0, 0, 'oops')
        Timer(5000, self)

    def onCellClicked(self, grid, row, col):
        if row > 0 and col > 0 and col < 5:
            w = self.getWidget(0, col)
            w.setText(self.getText(row, col))


class LoggerApplication(VerticalPanel):

    def __init__(self):
        VerticalPanel.__init__(self)
        self.proxy = JSONProxy('/_jsonrpc/logger', ['log', 'query'])
        #tools = HorizontalPanel()
        #self.dropdown = ListBox()
        #for value in ['10', '20', '50', '100']:
        #    self.dropdown.addItem(value, value)
        #self.dropdown.setSelectedIndex(1)
        #tools.add(self.dropdown)
        #self.dropdown.addChangeListener(self)
        #self.add(tools)
        self.grid = LoggerList(self)
        self.add(self.grid)
        self.grid.startUpdate()

    def onChange(self, listbox):
        self.grid.setBatchSize(
                int(self.dropdown.get(self.dropdown.getSelectedIndex()))
                )


if listRoot is not None:
    listRoot.add(LoggerApplication())

